package labrom.usage.client;

import java.util.List;
import java.util.Map;

import labrom.usage.shared.Props;
import labrom.usage.shared.Udi;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.PieChart;
import com.google.gwt.visualization.client.visualizations.PieChart.Options;


public class UsageData implements EntryPoint {

	/**
	 * Create a remote service proxy to talk to the server-side data service.
	 */
	private final DataServiceAsync dataService = GWT.create(DataService.class);
	
	private Label messages;
	private Props props;
	private boolean visualizationReady = false;
	private boolean propsReady = false;
	
	public void onModuleLoad() {
		
		messages = new Label();
		RootPanel.get("messages").add(messages);
		messages.setText("Initializing...");
		


		/* Create UI */
		final ListBox versions = new ListBox();
		versions.setEnabled(false);

		final Button b1 = new Button();
		b1.setText("All");
		b1.setEnabled(false);
		b1.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				displayData(getSelectedAppVersion(versions) , 0);
			}
		});
		final Button b2 = new Button();
		b2.setText("Last Month");
		b2.setEnabled(false);
		b2.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				displayData(getSelectedAppVersion(versions), 30);
			}
		});
		final Button b3 = new Button();
		b3.setText("Last Week");
		b3.setEnabled(false);
		b3.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				displayData(getSelectedAppVersion(versions), 7);
			}
		});
		final Button b4 = new Button();
		b4.setText("Last 24 Hours");
		b4.setEnabled(false);
		b4.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				displayData(getSelectedAppVersion(versions), 1);
			}
		});
		final RootPanel toolbar = RootPanel.get("toolbar");
		
		toolbar.add(versions);
		toolbar.add(b4);
		toolbar.add(b3);
		toolbar.add(b2);
		toolbar.add(b1);

		
		
		// Create a callback to be called when the visualization API
		// has been loaded.
		Runnable onLoadCallback = new Runnable() {
			public void run() {
				visualizationReady = true;
				if(propsReady) {
					b1.setEnabled(true);
					b2.setEnabled(true);
					b3.setEnabled(true);
					b4.setEnabled(true);
					fillVersions(versions);
					versions.setEnabled(true);
					messages.setText("Ready");
				}
			}
		};

		// Load the visualization api, passing the onLoadCallback to be called
		// when loading is done.
		VisualizationUtils.loadVisualizationApi(onLoadCallback, PieChart.PACKAGE);
		
		dataService.getProps(new AsyncCallback<Props>() {
			
			@Override
			public void onSuccess(Props result) {
				props = result;
				propsReady = true;
				if(visualizationReady) {
					b1.setEnabled(true);
					b2.setEnabled(true);
					b3.setEnabled(true);
					b4.setEnabled(true);
					fillVersions(versions);
					versions.setEnabled(true);
					messages.setText("Ready");
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				messages.setText("Failed to load properties");
			}
		});
	}
	
	private int getSelectedAppVersion(final ListBox versions) {
		return Integer.parseInt(versions.getValue(versions.getSelectedIndex()));
	}

	
	private void fillVersions(ListBox versions) {
		while(versions.getItemCount() < 0)
			versions.removeItem(0);
		for(int i = props.appVersionMin; i <= props.appVersionMax; i ++) {
			String ver = String.valueOf(i);
			versions.addItem("Version " + ver, ver);
		}
	}
	
	private void displayData(int version, int nDays) {
		messages.setText("Creating chart...");
		long ts = 0;
		if(nDays > 0)
			ts = System.currentTimeMillis() - nDays * 24 * 3600000;
		AsyncCallback<List<Udi>> callback = new AsyncCallback<List<Udi>>() {
							public void onFailure(Throwable caught) {
								messages.setText("Chart failed :(");
							}

							public void onSuccess(List<Udi> result) {
								// Create a pie chart visualization.
								PieChart pie = new PieChart(createTable(result), createOptions());
								RootPanel.get("chart").clear();
								RootPanel.get("chart").add(pie);
								messages.setText("Ready");
							}
						};
		if(version > 0)
			dataService.findAllSince(ts, version, callback);
		else
			dataService.findAllSince(ts, callback);
	}
	
	private AbstractDataTable createTable(List<Udi> udis) {
		DataTable data = DataTable.create();
		data.addColumn(ColumnType.STRING, "Type ID");
		data.addColumn(ColumnType.NUMBER, "Count");
		

		TypeIdCount counts = new TypeIdCount(udis);
		
		float minval = 0;
		if(props != null)
			minval = udis.size() / 100 * props.pieChartSliceThreshold;
		int rowIndex = 0;
		long othersVal = 0;
		for(Map.Entry<Long, Integer> e : counts.entrySet()) {
			Long id = e.getKey();
			int val = e.getValue();
			if(val < minval) {
				othersVal += val;
			} else {
				int screenId = (int)(id / 1000000000000l);
				int typeId = (int)((id % 1000000000000l) / 1000000);
				String screen = null;
				String type = null;
				if(props != null) {
					screen = props.screenCaptions.get(screenId);
					type = props.typeCaptions.get(typeId);
				}
				StringBuilder name = new StringBuilder();
				if(screen != null)
					name.append(screen);
				else if(screenId > 0)
					name.append(String.valueOf(screenId));
				if(name.length() > 0)
					name.append('-');
				if(type != null)
					name.append(type);
				else if(typeId > 0)
					name.append(String.valueOf(typeId));
				name.append('-').append(String.valueOf(id % 1000000));
				data.addRow();
				data.setValue(rowIndex, 0, name.toString());
				data.setValue(rowIndex, 1, val);
				rowIndex ++;
			}
		}
		if(othersVal > 0) {
			data.addRow();
			data.setValue(rowIndex, 0, "Others");
			data.setValue(rowIndex, 1, othersVal);
		}
		
		return data;
	}

	private Options createOptions() {
		Options options = Options.create();
		options.setWidth(props.pieChartWidth);
		options.setHeight(props.pieChartHeight);
		options.set3D(true);
		options.setTitle("Repartition of Type IDs");
		options.setLegendFontSize(props.pieChartLegendFontSize);
		return options;
	}

	

//	/**
//	 * This is the entry point method.
//	 */
//	public void onModuleLoad() {
//		final Button sendButton = new Button("Send");
//		final TextBox nameField = new TextBox();
//		nameField.setText("GWT User");
//		final Label errorLabel = new Label();
//
//		// We can add style names to widgets
//		sendButton.addStyleName("sendButton");
//
//		// Add the nameField and sendButton to the RootPanel
//		// Use RootPanel.get() to get the entire body element
//		RootPanel.get("nameFieldContainer").add(nameField);
//		RootPanel.get("sendButtonContainer").add(sendButton);
//		RootPanel.get("errorLabelContainer").add(errorLabel);
//
//		// Focus the cursor on the name field when the app loads
//		nameField.setFocus(true);
//		nameField.selectAll();
//
//		// Create the popup dialog box
//		final DialogBox dialogBox = new DialogBox();
//		dialogBox.setText("Remote Procedure Call");
//		dialogBox.setAnimationEnabled(true);
//		final Button closeButton = new Button("Close");
//		// We can set the id of a widget by accessing its Element
//		closeButton.getElement().setId("closeButton");
//		final Label textToServerLabel = new Label();
//		final HTML serverResponseLabel = new HTML();
//		VerticalPanel dialogVPanel = new VerticalPanel();
//		dialogVPanel.addStyleName("dialogVPanel");
//		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
//		dialogVPanel.add(textToServerLabel);
//		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
//		dialogVPanel.add(serverResponseLabel);
//		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
//		dialogVPanel.add(closeButton);
//		dialogBox.setWidget(dialogVPanel);
//
//		// Add a handler to close the DialogBox
//		closeButton.addClickHandler(new ClickHandler() {
//			public void onClick(ClickEvent event) {
//				dialogBox.hide();
//				sendButton.setEnabled(true);
//				sendButton.setFocus(true);
//			}
//		});
//
//		// Create a handler for the sendButton and nameField
//		class MyHandler implements ClickHandler, KeyUpHandler {
//			/**
//			 * Fired when the user clicks on the sendButton.
//			 */
//			public void onClick(ClickEvent event) {
//				sendNameToServer();
//			}
//
//			/**
//			 * Fired when the user types in the nameField.
//			 */
//			public void onKeyUp(KeyUpEvent event) {
//				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
//					sendNameToServer();
//				}
//			}
//
//			/**
//			 * Send the name from the nameField to the server and wait for a response.
//			 */
//			private void sendNameToServer() {
//				// First, we validate the input.
//				errorLabel.setText("");
//				String textToServer = nameField.getText();
//				if (!FieldVerifier.isValidName(textToServer)) {
//					errorLabel.setText("Please enter at least four characters");
//					return;
//				}
//
//				// Then, we send the input to the server.
//				sendButton.setEnabled(false);
//				textToServerLabel.setText(textToServer);
//				serverResponseLabel.setText("");
//				greetingService.greetServer(textToServer,
//						new AsyncCallback<String>() {
//							public void onFailure(Throwable caught) {
//								// Show the RPC error message to the user
//								dialogBox
//										.setText("Remote Procedure Call - Failure");
//								serverResponseLabel
//										.addStyleName("serverResponseLabelError");
//								serverResponseLabel.setHTML(SERVER_ERROR);
//								dialogBox.center();
//								closeButton.setFocus(true);
//							}
//
//							public void onSuccess(String result) {
//								dialogBox.setText("Remote Procedure Call");
//								serverResponseLabel
//										.removeStyleName("serverResponseLabelError");
//								serverResponseLabel.setHTML(result);
//								dialogBox.center();
//								closeButton.setFocus(true);
//							}
//						});
//			}
//		}
//
//		// Add a handler to send the name to the server
//		MyHandler handler = new MyHandler();
//		sendButton.addClickHandler(handler);
//		nameField.addKeyUpHandler(handler);
//	}
}
